package com.bscc.common.directive;

import com.bscc.common.model.Menu;
import com.bscc.common.model.User;
import com.jfinal.kit.StrKit;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.stat.Scope;

import javax.servlet.http.HttpSession;
import java.io.Writer;
import java.util.List;

public class IfHasAuth extends Directive {
    private Expr valueExpr;
    public void setExprList(ExprList exprList) {
        this.valueExpr = exprList.getExprArray()[0];
    }

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        HttpSession session = (HttpSession) scope.get("session");
        if (null != session) {
            User user = (User) session.getAttribute("user");
            String actionKey = (String) valueExpr.eval(scope);
            if (auth(user, actionKey)) {
                stat.exec(env, scope, writer);
            }
        }
    }

    public boolean hasEnd() {
        return true;
    }

    /**
     * 判断用户是否有权限
     * @param user --用户对象
     * @param actionKey --访问地址
     * @return
     */
    private boolean auth(User user, String actionKey) {
        if (user != null && StrKit.notBlank(actionKey)) {
            List<Menu> authMenus = user.getMenuList();
            if(null != authMenus && authMenus.size() > 0)
            {
                for (Menu m:authMenus) {
                    if (actionKey.equals(m.getPermission())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
